import SingleBase from '../base/SingleBase';
import {cUI} from '../../config/Config';

export default class Pool extends SingleBase {
    pools: Map<string | Function, cc.NodePool> = new Map();

    createPool(name: string): cc.NodePool {
        let pool: cc.NodePool = new cc.NodePool(name);
        this.pools.set(pool.poolHandlerComp, pool);
        return pool;
    }

    async get(url_name: string): Promise<cc.Node> {
        let pool: cc.NodePool = this.pools.get(url_name) || this.createPool(url_name);
        if (pool.size() > 0) {
            return pool.get();
        }
        return cUI.createNode(url_name).then(node => {
            return node;
        });
    }

    put(node: cc.Node) {
        if (!node) {
            return;
        }
        let pool: cc.NodePool = this.pools.get(node.url_name);
        if (pool) {
            pool.put(node);
            // console.log('put ' + node.name);
        } else {
            // console.log('destroy ' + node.name);
            node.destroy();
        }
    }
    puts(nodes: cc.Node[]) {
        nodes.forEach(value => {
            this.put(value);
        })
    }
    clear(url_name: string) {
        let pool: cc.NodePool = this.pools.get(url_name);
        if (pool) {
            pool.clear();
            cc.resources.release(url_name);
            // console.log('clear pool ' + url_name);
        }
    }

    clearAll() {
        this.pools.forEach((value: cc.NodePool) => {
            value.clear();
        })
    }
}